package cn.com.zpark;

import cn.com.zpark.bean.User;
import cn.com.zpark.utils.DruidUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @PackageName: cn.com.zpark
 * @ClassName: LoginServlet
 * @Description:
 * @author: RZS
 * @date: 2021/12/11  15:44
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 获取session
        HttpSession session = request.getSession();

        Connection conn = null;
        PreparedStatement stat = null;
        ResultSet res = null;

        // 声明user对象
        User user = null;

        try {
            // 获取数据库连接对象
            conn = DruidUtils.getConn();
            // 编写sql语句
            String sql = "select * from user where uname=?";
            // 获取sql执行对象
            stat = conn.prepareStatement(sql);
            // 替换占位符
            stat.setString(1, username);
            // 执行sql
            res = stat.executeQuery();
            // 循环遍历结果集
            while (res.next()) {
                // 创建user对象
                user = new User();
                user.setId(res.getInt("id"));
                user.setUname(res.getString("uname"));
                user.setPwd(res.getString("pwd"));
            }

            // 判断user是否为null
            if(user == null){
                // 绑定登录错误信息到session对象
                session.setAttribute("msg", "用户名或者密码错误");
                // 重定向到登录页面
                response.sendRedirect(request.getContextPath()+"/view/index.jsp");
            }

            // user有数据, 判断密码是否相等
            if(user.getPwd().equals(password)){
                // 登录成功
                response.getWriter().write("<h1>Success</h1>");
            }else{
                // 密码不一致，登录失败
                // 绑定登录错误信息到session对象
                session.setAttribute("msg", "用户名或者密码错误");
                // 重定向到登录页面
                response.sendRedirect(request.getContextPath()+"/view/index.jsp");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭资源
            DruidUtils.close(res, stat, conn);
        }

    }
}
